package com.cloudcms.web.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.cloudcms.web.common.BusinessException;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * UEditor文件上传辅助类
 *
 */
public class Uploader {
	// 输出文件地址
	private String url = "";
	// 上传文件名
	private String fileName = "";
	// 状态
	private String state = "";
	// 文件类型
	private String type = "";
	// 原始文件名
	private String originalName = "";
	// 文件大小
	private long size = 0;

	private HttpServletRequest request = null;
	private String title = "";

	// 保存路径
	private String savePath = "upload";
	// 文件允许格式

	// 文件大小限制，单位KB
	private int maxSize = 10000;
	
	private HashMap<String, String> errorInfo = new HashMap<String, String>();

	public Uploader(HttpServletRequest request) {
		this.request = request;
		HashMap<String, String> tmp = this.errorInfo;
		tmp.put("SUCCESS", "SUCCESS"); //默认成功
		tmp.put("NOFILE", "未包含文件上传域");
		tmp.put("TYPE", "不允许的文件格式");
		tmp.put("SIZE", "文件大小超出限制");
		tmp.put("ENTYPE", "请求类型ENTYPE错误");
		tmp.put("REQUEST", "上传请求异常");
		tmp.put("IO", "IO异常");
		tmp.put("DIR", "目录创建失败");
		tmp.put("UNKNOWN", "未知错误");

	}
	public static String saveFile(String bootPath,MultipartFile file,String visitUrl){
		String filePath = "";  //由bootPath和日期组合而成
		SimpleDateFormat formater = new SimpleDateFormat("yyyy/MM/dd");
		String ext = getFileExt(file.getOriginalFilename());
		if(!checkFileType(file.getOriginalFilename())) throw new BusinessException(701L,"不允许上传"+ext+"格式的文件");

		String uuid = UUID.randomUUID().toString().replaceAll("-","").substring(0,8);//用uuid作为保存时的文件名，防止中文乱码
		if (visitUrl == null || "".equals(visitUrl)) {
			visitUrl = "/"+formater.format(new Date())+"/"+uuid+ext;
		}
		// 拼接保存路径
		if (filePath == null || "".equals(filePath)) {
			filePath = bootPath + visitUrl;
		}

		File f = new File(filePath);
		if (!f.exists()) {
			f.getParentFile().mkdirs();
		}
		OutputStream out;
		try {
			out = new FileOutputStream(f);
			FileCopyUtils.copy(file.getInputStream(), out);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			Runtime.getRuntime().exec("chmod 755 -R " + filePath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return visitUrl;
	}
	/**
	 * 文件类型判断
	 * 
	 * @param fileName
	 * @return
	 */
	private static boolean checkFileType(String fileName) {
		String[] allowFiles = { ".rar", ".doc", ".docx", ".zip", ".pdf",".txt", ".swf", ".wmv", ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
		Iterator<String> type = Arrays.asList(allowFiles).iterator();
		while (type.hasNext()) {
			String ext = type.next();
			if (fileName.toLowerCase().endsWith(ext)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @return string
	 */
	public static String getFileExt(String fileName) {
		return fileName.substring(fileName.lastIndexOf("."));
	}

	/**
	 * 依据原始文件名生成新文件名
	 * @return
	 */
	public static String getName(String fileName) {
		Random random = new Random();
		return random.nextInt(10000) +System.currentTimeMillis() + Uploader.getFileExt(fileName);
	}

	/**
	 * 根据字符串创建本地目录 并按照日期建立子目录返回
	 * @param path 
	 * @return 
	 */
	private String getFolder(String path) {
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
		path += "/" + formater.format(new Date());
		File dir = new File(this.getPhysicalPath(path));
		if (!dir.exists()) {
			try {
				dir.mkdirs();
			} catch (Exception e) {
				this.state = this.errorInfo.get("DIR");
				return "";
			}
		}
		return path;
	}

	/**
	 * 根据传入的虚拟路径获取物理路径
	 * 
	 * @param path
	 * @return
	 */
	private String getPhysicalPath(String path) {
		String servletPath = this.request.getServletPath();
		String realPath = this.request.getSession().getServletContext()
				.getRealPath(servletPath);
		return new File(realPath).getParent() +"/" +path;
	}
}
